package cn.cas.mango.util.RequestUtil;

import cn.cas.mango.dto.HotSpotNews;
import cn.cas.mango.dto.param.BaseTimeParam;
import cn.cas.mango.service.ConfigService;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.StringTermsBucket;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GroupByRequest {
  @Autowired
  ElasticsearchClient elasticsearchClient;
  @Autowired
  ConfigService configService;
  public List<Map<String, Object>> getHotSpotNews(BaseTimeParam baseTimeParam, String field) {
    String endDate = baseTimeParam.getEndDate();
    String startDate = baseTimeParam.getStartDate();
    SearchRequest searchRequest = SearchRequest.of(x -> x.index(configService.getIndex())
        .query(q -> q.range(r -> r.field("fssj").gte(JsonData.of(startDate))
            .lte(JsonData.of(endDate))))
        .aggregations("group_by_field",
            a -> a.terms(t -> t.field(field).size(1000))));
    SearchResponse<Map> searchResponse;
    try {
      searchResponse = elasticsearchClient.search(searchRequest, Map.class);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    List<Map<String, Object>> hotSpotNewsList = new ArrayList<>();
    Aggregate aggregate = searchResponse.aggregations().get("group_by_field");
    if (aggregate != null && aggregate.isSterms()) {
      List<StringTermsBucket> buckets = aggregate.sterms().buckets().array();
      for (StringTermsBucket bucket : buckets) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", bucket.key().stringValue());
        long l = bucket.docCount();
        map.put("count", l );
        hotSpotNewsList.add(map);
      }
    }
    hotSpotNewsList.sort((map1, map2) -> Long.compare((long) map2.get("count"), (long) map1.get("count")));

    return hotSpotNewsList;
  }
}
